package algorithm;

import java.util.HashMap;

class  Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

public class CopyofaRandomLinkedList {
    public  Node copyRandomList(Node head) {
        //首先建立一个HashMap,建立旧结点到新结点的映射
        Node cur = head;
        HashMap<Node,Node> hashMap = new HashMap<>();

        while(cur != null) {
            Node newCur = new Node(cur.val);
            hashMap.put(cur,newCur);
            cur = cur.next;
        }

        //让cur再次指回原链表的头部
        cur = head;
        Node newHead = hashMap.get(cur);

        while(cur != null) {
            // 核心代码
            hashMap.get(cur).next = hashMap.get(cur.next);
            hashMap.get(cur).random = hashMap.get(cur.random);
            cur = cur.next;
        }

        return newHead;
    }
}

